package com.panvan.android;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class WebViewChromeListener extends WebChromeClient {

    public ValueCallback<Uri[]> uploadMessage;
    public  boolean isCapture;
    public Uri imageUri;
    MainActivity activity;

    WebViewChromeListener(MainActivity activity){
        super();
        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder =new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        this.activity=activity;
    }


    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }
    @Override
    public boolean onShowFileChooser( WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        try {
            imageUri=null;
            isCapture = fileChooserParams.isCaptureEnabled();
            uploadMessage = filePathCallback;
            if (isCapture) {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                File photo = createTempImageFile();
                imageUri = Uri.fromFile(photo);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                activity.cameraLauncher.launch(intent);

                return true;
            }
            String [] fileType= fileChooserParams.getAcceptTypes();
            if(fileType.length==1&&fileType[0].equals("")){
                fileType[0]="*/*";
            }
            String fileTypeStr=String.join(",",fileType);
            Intent  intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType(fileTypeStr);
            activity.checkFileLauncher.launch(intent);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }
     File createTempImageFile() throws IOException {
        File destFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        destFolder.mkdirs();
        String dateTimeString =new Date().getTime()+"";
        File imageFile = File.createTempFile(dateTimeString + "-", ".png", destFolder);
        return imageFile;
    }
}
